package com.socket.nio.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @auther zhangwj
 * @date 2020/6/14 1:26 下午
 */
public class NioServer {

    private static final int BUF_SIZE = 1024;

    public void myServer(int port) throws IOException {
        // 选择器
        Selector selector = Selector.open();

        // 绑定端口
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(port));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);


        while (true) {
            int count = selector.select();
            if (count == 0) {
                continue;
            }
            Iterator<SelectionKey> selectionKeys = selector.selectedKeys().iterator();
            while (selectionKeys.hasNext()) {
                SelectionKey selectionKey = selectionKeys.next();
                if (selectionKey.isAcceptable()) {
                    ServerSocketChannel ssChannel = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel sc = ssChannel.accept();
                    sc.configureBlocking(false);
                    sc.register(selectionKey.selector(), SelectionKey.OP_READ, ByteBuffer.allocateDirect(BUF_SIZE));
                    selectionKeys.remove();
                }
                if (selectionKey.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
                    long bytesRead = socketChannel.read(byteBuffer);
                    while (bytesRead > 0) {
                        byteBuffer.flip();
                        System.out.println(byteBuffer.get());
                    }
                    if (bytesRead == -1) {
                        socketChannel.close();
                    }
                }
            }
        }

    }

    public static void main(String[] args) throws IOException {
        NioServer nioServer = new NioServer();
        nioServer.myServer(8080);
    }
}
